package com.xin.spring.project.servlet.controller;

import com.alibaba.fastjson.JSON;
import com.xin.spring.project.servlet.model.User;
import com.xin.spring.project.servlet.service.ITestService;
import com.xin.spring.project.servlet.service.impl.TestServiceImpl;
import com.xin.spring.project.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 测试控制器
 * @author xinyue
 */
@WebServlet(name = "testController", urlPatterns = "/test")
public class TestController extends HttpServlet {

    ITestService testService = new TestServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");

        String name = req.getParameter("name");
        String tel = req.getParameter("tel");
        User user = new User();
        user.setName(name);
        user.setTel(tel);
        Result result = new Result();
        try {
            testService.insertUser(user);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("500");
            result.setMsg(e.toString());
        }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(JSON.toJSONString(result));
    }
}
